const axios = require('axios');

// 测试配置
const BASE_URL = 'http://localhost:3001';
const TEST_USER = {
  loginname: '13800138000',
  password: '123456'
};

const TEST_ADMIN = {
  adminname: 'admin',
  password: '123456'
};

// 存储测试数据
let testData = {
  userToken: '',
  adminToken: '',
  userid: '',
  orderid: '',
  reviewid: ''
};

// 请求辅助函数
async function makeRequest(method, url, data = null, token = null) {
  try {
    const config = {
      method,
      url: `${BASE_URL}${url}`,
      headers: {
        'Content-Type': 'application/json'
      },
      timeout: 10000 // 10秒超时
    };
    
    if (token) {
      config.headers.token = token;
    }
    
    if (data) {
      if (method.toLowerCase() === 'get') {
        config.params = data;
      } else {
        config.data = data;
      }
    }
    
    const response = await axios(config);
    return {
      success: true,
      data: response.data
    };
  } catch (error) {
    console.log('请求详细错误信息:');
    console.log('- URL:', `${BASE_URL}${url}`);
    console.log('- Method:', method);
    console.log('- Error Code:', error.code);
    console.log('- Error Message:', error.message);
    if (error.response) {
      console.log('- Response Status:', error.response.status);
      console.log('- Response Data:', error.response.data);
    }
    
    return {
      success: false,
      error: error.response ? error.response.data : error.message,
      status: error.response ? error.response.status : error.code || 'NETWORK_ERROR'
    };
  }
}

// 用户注册
async function registerUser() {
  console.log('\n=== 1. 用户注册 ===');
  const result = await makeRequest('POST', '/api/user/reg', TEST_USER);
  
  if (result.success) {
    if (result.data.code === '200') {
      console.log('✓ 用户注册成功');
      return true;
    } else if (result.data.code === '1001') {
      console.log('✓ 用户已存在，跳过注册');
      return true;
    } else {
      console.log('✗ 用户注册失败:', result.data.message);
      return false;
    }
  } else {
    console.log('✗ 用户注册请求失败:', result.error);
    return false;
  }
}

// 用户登录
async function loginUser() {
  console.log('\n=== 2. 用户登录 ===');
  const result = await makeRequest('POST', '/api/user/login', {
    loginname: TEST_USER.loginname,
    password: TEST_USER.password
  });
  
  if (result.success && result.data.code === '200') {
    testData.userToken = result.data.data.token;
    testData.userid = result.data.data.userid;
    console.log('✓ 用户登录成功, userid:', testData.userid);
    return true;
  } else {
    console.log('✗ 用户登录失败:', result.success ? result.data.message : result.error);
    return false;
  }
}

// 管理员登录
async function loginAdmin() {
  console.log('\n=== 3. 管理员登录 ===');
  const result = await makeRequest('POST', '/admin/admin/login', TEST_ADMIN);
  
  if (result.success && result.data.code === '200') {
    testData.adminToken = result.data.data.token;
    console.log('✓ 管理员登录成功');
    return true;
  } else {
    console.log('✗ 管理员登录失败:', result.success ? result.data.message : result.error);
    return false;
  }
}

// 创建测试订单
async function createTestOrder() {
  console.log('\n=== 4. 创建测试订单 ===');
  
  // 首先添加测试商品到购物车
  const cartData = {
    userid: testData.userid,
    proid: 'pro_36d07f55-68c3-4891-8c77-3c349c44d1be', // 使用实际存在的商品ID
    num: 1
  };
  
  // 先清空购物车
  await makeRequest('POST', '/api/cart/removeall', { userid: testData.userid }, testData.userToken);
  
  // 添加商品到购物车
  const cartResult = await makeRequest('POST', '/api/cart/add', cartData, testData.userToken);
  
  if (!cartResult.success || cartResult.data.code !== '200') {
    console.log('✗ 添加商品到购物车失败');
    return false;
  }
  
  // 更新地址信息
  const addressData = {
    userid: testData.userid,
    name: '测试用户',
    tel: '13800138000',
    province: '北京市',
    city: '北京市',
    county: '朝阳区',
    addressDetail: '测试地址'
  };
  
  await makeRequest('POST', '/api/order/updateOrderAddress', addressData, testData.userToken);
  
  // 创建订单
  const orderData = {
    userid: testData.userid
  };

  const orderResult = await makeRequest('POST', '/api/order/addOrder', orderData, testData.userToken);

  if (orderResult.success && orderResult.data.code === '200') {
    const orderTime = orderResult.data.time; // 使用服务器返回的时间戳
    
    // 等待一小段时间确保订单创建完成
    await new Promise(resolve => setTimeout(resolve, 500));
    
    // 通过确认订单接口获取刚创建的订单信息
    const confirmResult = await makeRequest('GET', '/api/order/confirmOrder', {
      userid: testData.userid,
      time: orderTime
    }, testData.userToken);

    if (confirmResult.success && confirmResult.data.code === '200' && confirmResult.data.data.length > 0) {
      testData.orderid = confirmResult.data.data[0].orderid;
      testData.orderTime = orderTime; // 保存时间戳用于后续清理
      console.log('✓ 测试订单创建成功, orderid:', testData.orderid);
      return true;
    } else {
      console.log('✗ 无法获取创建的订单ID');
      return false;
    }
  } else {
    console.log('✗ 测试订单创建失败:', orderResult.success ? orderResult.data.message : orderResult.error);
    return false;
  }
}

// 更新订单状态为已完成
async function updateOrderToCompleted() {
  console.log('\n=== 5. 更新订单状态为已完成 ===');
  
  const result = await makeRequest('GET', '/admin/order/updateStatus', {
    orderid: testData.orderid,
    status: 4 // 已完成
  }, testData.adminToken);
  
  if (result.success && result.data.code === '200') {
    console.log('✓ 订单状态更新为已完成成功');
    return true;
  } else {
    console.log('✗ 订单状态更新失败:', result.success ? result.data.message : result.error);
    return false;
  }
}

// 提交订单评价
async function submitReview() {
  console.log('\n=== 6. 提交订单评价 ===');
  
  const reviewData = {
    orderid: testData.orderid,
    userid: testData.userid,
    rating: 5,
    content: '商品质量很好，物流很快，非常满意！'
  };
  
  const result = await makeRequest('POST', '/api/review/submit', reviewData, testData.userToken);
  
  if (result.success && result.data.code === '200') {
    testData.reviewid = result.data.data.reviewid;
    console.log('✓ 评价提交成功, reviewid:', testData.reviewid);
    return true;
  } else {
    console.log('✗ 评价提交失败:', result.success ? result.data.message : result.error);
    return false;
  }
}

// 验证订单状态更新为已完成
async function verifyOrderCompleted() {
  console.log('\n=== 7. 验证订单状态更新为已完成 ===');
  
  const result = await makeRequest('GET', '/api/order/detail/' + testData.orderid, {
    userid: testData.userid
  }, testData.userToken);
  
  if (result.success && result.data.code === '200') {
    const orderStatus = result.data.data.orderInfo.status;
    if (orderStatus === 4) {
      console.log('✓ 订单状态已自动更新为已完成');
      return true;
    } else {
      console.log('✗ 订单状态未更新，当前状态:', orderStatus);
      return false;
    }
  } else {
    console.log('✗ 获取订单详情失败:', result.success ? result.data.message : result.error);
    return false;
  }
}

// 获取订单评价
async function getOrderReview() {
  console.log('\n=== 8. 获取订单评价 ===');
  
  const result = await makeRequest('GET', '/api/review/order/' + testData.orderid, {
    userid: testData.userid
  }, testData.userToken);
  
  if (result.success && result.data.code === '200') {
    console.log('✓ 获取订单评价成功');
    console.log('  评价内容:', result.data.data.content);
    console.log('  评分:', result.data.data.rating);
    return true;
  } else {
    console.log('✗ 获取订单评价失败:', result.success ? result.data.message : result.error);
    return false;
  }
}

// 管理员查看评价列表
async function adminViewReviews() {
  console.log('\n=== 9. 管理员查看评价列表 ===');
  
  const result = await makeRequest('GET', '/admin/review/list', {
    page: 1,
    pageSize: 10
  }, testData.adminToken);
  
  if (result.success && result.data.code === '200') {
    console.log('✓ 管理员获取评价列表成功');
    console.log('  评价总数:', result.data.data.total);
    return true;
  } else {
    console.log('✗ 管理员获取评价列表失败:', result.success ? result.data.message : result.error);
    return false;
  }
}

// 清理测试数据
async function cleanupTestData() {
  console.log('\n=== 10. 清理测试数据 ===');
  
  try {
    // 删除测试订单（通过管理员接口）
    if (testData.orderid && testData.adminToken) {
      const deleteOrderResult = await makeRequest('DELETE', '/admin/order/delete', {
        orderid: testData.orderid
      }, testData.adminToken);
      
      if (deleteOrderResult.success) {
        console.log('✓ 测试订单已删除');
      }
    }
    
    // 删除测试评价（通过管理员接口）
    if (testData.reviewid && testData.adminToken) {
      const deleteReviewResult = await makeRequest('DELETE', '/admin/review/delete', {
        reviewid: testData.reviewid
      }, testData.adminToken);
      
      if (deleteReviewResult.success) {
        console.log('✓ 测试评价已删除');
      }
    }
    
    console.log('✓ 测试数据清理完成');
    return true;
  } catch (error) {
    console.log('✗ 清理测试数据失败:', error.message);
    return false;
  }
}

// 预清理测试数据（在测试开始前）
async function preCleanupTestData() {
  console.log('\n=== 预清理测试数据 ===');
  
  try {
    // 先尝试登录管理员获取token
    const adminResult = await makeRequest('POST', '/admin/admin/login', TEST_ADMIN);
    
    if (adminResult.success && adminResult.data.code === '200') {
      const adminToken = adminResult.data.data.token;
      
      let deletedReviews = 0;
      let deletedOrders = 0;
      
      // 删除可能存在的测试用户的所有评价
      const reviewListResult = await makeRequest('GET', '/admin/review/list', {
        page: 1,
        pageSize: 100
      }, adminToken);
      
      if (reviewListResult.success && reviewListResult.data.code === '200') {
        const reviews = reviewListResult.data.data.list || [];
        
        // 删除包含测试用户ID的评价
        for (const review of reviews) {
          if (review.userid && review.userid.includes('user_')) {
            const deleteResult = await makeRequest('DELETE', '/admin/review/delete', {
              reviewid: review.reviewid
            }, adminToken);
            if (deleteResult.success) {
              deletedReviews++;
            }
          }
        }
      }
      
      // 删除可能存在的测试用户的所有订单
      const orderListResult = await makeRequest('GET', '/admin/order/list', {
        page: 1,
        pageSize: 100
      }, adminToken);
      
      if (orderListResult.success && orderListResult.data.code === '200') {
        const orders = orderListResult.data.data.list || [];
        
        // 删除包含测试用户ID的订单
        for (const order of orders) {
          if (order.userid && order.userid.includes('user_')) {
            const deleteResult = await makeRequest('DELETE', '/admin/order/delete', {
              orderid: order.orderid
            }, adminToken);
            if (deleteResult.success) {
              deletedOrders++;
            }
          }
        }
      }
      
      // 额外清理：删除可能存在的固定测试订单ID
      const fixedTestOrderIds = ['order_test_1755851988176'];
      for (const orderid of fixedTestOrderIds) {
        const deleteResult = await makeRequest('DELETE', '/admin/order/delete', {
          orderid: orderid
        }, adminToken);
        if (deleteResult.success) {
          deletedOrders++;
        }
      }
      
      console.log(`✓ 预清理完成，删除了 ${deletedReviews} 条评价和 ${deletedOrders} 个订单`);
    }
    
    return true;
  } catch (error) {
    console.log('⚠️  预清理失败，继续测试:', error.message);
    return true; // 预清理失败不影响测试继续
  }
}

// 主测试流程
async function runIntegrationTest() {
  console.log('开始订单评价功能集成测试...');
  console.log('测试服务器:', BASE_URL);
  
  const steps = [
    preCleanupTestData,
    registerUser,
    loginUser,
    loginAdmin,
    createTestOrder,
    updateOrderToCompleted,
    submitReview,
    verifyOrderCompleted,
    getOrderReview,
    adminViewReviews,
    cleanupTestData
  ];
  
  let passedSteps = 0;
  
  for (let i = 0; i < steps.length; i++) {
    const stepResult = await steps[i]();
    if (stepResult) {
      passedSteps++;
    } else {
      console.log('\n❌ 测试在步骤', i + 1, '失败，停止后续测试');
      break;
    }
    
    // 在某些步骤之间添加延迟
    if (i < steps.length - 1) {
      await new Promise(resolve => setTimeout(resolve, 500));
    }
  }
  
  console.log('\n=== 集成测试结果 ===');
  console.log(`通过步骤: ${passedSteps}/${steps.length}`);
  
  if (passedSteps === steps.length) {
    console.log('🎉 所有集成测试通过！订单评价功能工作正常。');
  } else {
    console.log('⚠️  部分测试失败，请检查相关功能。');
  }
}

// 运行测试
if (require.main === module) {
  runIntegrationTest().catch(console.error);
}

module.exports = {
  runIntegrationTest,
  testData
};